package com.baizhi.service.impl;

import com.baizhi.dao.CityDAO;
import com.baizhi.dao.TagDAO;
import com.baizhi.entity.City;
import com.baizhi.entity.Tag;
import com.baizhi.service.CityService;
import com.baizhi.service.tagService;
import com.baizhi.util.MybatisUtil;

import java.util.List;

public class CityServiceImpl implements CityService {

    @Override  //查询所有
    public List<City> queryAll() {
        List<City> list = null;
        try {

            CityDAO cd = (CityDAO) MybatisUtil.getMapper(CityDAO.class);
            list = cd.selectAll();
            MybatisUtil.commit();

        }catch (Exception e){
            e.printStackTrace();
            MybatisUtil.rollback();  //向上回滚
            throw new RuntimeException(e);
        }finally {
            MybatisUtil.close();  //关闭资源
        }
        return list;
    }


    @Override  //根据id 删除一条数据
    public void deleteById(int id) {

        try {

            CityDAO cd = (CityDAO) MybatisUtil.getMapper(CityDAO.class);
            cd.deleteById(id);
            MybatisUtil.commit();
        }catch (Exception e){
            e.printStackTrace();
            MybatisUtil.rollback();  //向上回滚
            throw new RuntimeException(e);

        }finally {
            MybatisUtil.close();  //关闭资源
        }
    }


    @Override  //插入一条数据
    public void insertCity(City city) {

        try{

            CityDAO cd = (CityDAO) MybatisUtil.getMapper(CityDAO.class);
            cd.insertCity(city);
            MybatisUtil.commit();
        }catch (Exception e){
            e.printStackTrace();
            MybatisUtil.rollback();  //向上回滚
            throw new RuntimeException(e);
        }finally {
            MybatisUtil.close();  //关闭资源
        }
    }



    @Override  ////根据页码查询数据  一页五条数据
    public List<City> queryByPage(int pageNumber) {
        CityDAO ed =(CityDAO) MybatisUtil.getMapper(CityDAO.class);
        //根据页号计算起始条数
        int beginCount = (pageNumber-1)*5;

        List<City> citys= ed.selectByPage(beginCount,5);
        MybatisUtil.close();
        return citys;
    }



    @Override     ////获取页数  根据总条数求得总页数
    public int getTotalPage() {

        CityDAO cd =(CityDAO) MybatisUtil.getMapper(CityDAO.class);
        //获取总条数
        int totalCount = cd.selectTotalCount();
        //根据总条数 计算总页数
        int totalPage = 0;
        if(totalCount % 5 == 0){
            totalPage = totalCount / 5 ;
        }else{
            totalPage = totalCount / 5 +1 ;
        }
        MybatisUtil.close();
        return totalPage;
    }
}
